<template>
  <div class="gray-page resident-detail-page">
    <nav-bar :title="`居民基础信息${title}`"></nav-bar>
    <div class="resident-detail-main page-main">
      <van-sticky class="page-scroll" :offset-top="44">
        <div class="resident-detail-upload" v-if="!$route.query.personCode">
          <div align="center">
            <van-uploader
              name="idCardFileList"
              v-model="idCardFileList"
              accept="image/*"
              :preview-image="false"
              :max-size="maxSize"
              :before-read="uploadBeforeRead"
              :after-read="uploadAfterRead"
            >
              <div class="van-uploader__input--yellow-large">
                <van-image
                  v-if="idCardFileList.length"
                  width="203px"
                  height="113px"
                  fit="cover"
                  style="border-radius: 12px"
                  :src="idCardFileList[idCardFileList.length - 1].content"
                />
                <template v-else>
                  <div class="upload-image">
                    <img src="@/assets/images/basic/icon_camera@2x.png" />
                  </div>
                  <div class="upload-text">请上传清晰完整的身份证正面照</div>
                </template>
              </div>
            </van-uploader>
          </div>
        </div>
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-collapse v-model="activeNames" :border="false">
            <van-collapse-item size="large" title="基础信息" name="1">
              <van-field
                required
                readonly
                clickable
                name="residentTypeName"
                v-model="formParams.residentTypeName"
                label="人口管理类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.residentTypeName"
                @click="dictOpenPopup('residentType')"
              />
              <van-field
                required
                name="personName"
                v-model="formParams.personName"
                label="姓名"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.personName"
              />
              <van-field
                name="formerName"
                v-model="formParams.formerName"
                label="曾用名"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.formerName"
              />
              <van-field
                required
                readonly
                clickable
                name="idTypeName"
                v-model="formParams.idTypeName"
                label="证件类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.idTypeName"
                @click="dictOpenPopup('idType')"
              />
              <van-field
                required
                name="idCard"
                v-model="formParams.idCard"
                label="证件号码"
                placeholder="请选择"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="formParams.idType === '111' ? rules.idCard : rules.passport"
                @blur="queryDetail"
              />
              <van-field
                required
                readonly
                clickable
                name="sexName"
                v-model="formParams.sexName"
                label="性别"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.sexName"
                @click="dictOpenPopup('sex')"
              />
              <van-field
                required
                readonly
                clickable
                name="nationalityName"
                v-model="formParams.nationalityName"
                label="民族"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.nationalityName"
                @click="dictOpenPopup('nationality')"
              />
              <van-field
                readonly
                clickable
                name="birthPlaceName"
                v-model="formParams.birthPlaceName"
                label="籍贯"
                placeholder="请选择"
                right-icon="arrow"
                @click="cascadeOpenPopup('birthPlace', '籍贯')"
              />
              <van-field
                readonly
                clickable
                name="birthday"
                v-model="formParams.birthday"
                label="出生日期"
                placeholder="请选择"
                right-icon="arrow"
                @click="dateOpenPopup('birthday')"
              />
              <van-field
                readonly
                clickable
                name="marriageName"
                v-model="formParams.marriageName"
                label="婚姻状况"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('marriage')"
              />
              <van-field
                readonly
                clickable
                name="politicName"
                v-model="formParams.politicName"
                label="政治面貌"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('politic')"
              />
              <van-field
                readonly
                clickable
                name="edulevelName"
                v-model="formParams.edulevelName"
                label="学历"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('edulevel')"
              />
              <van-field
                readonly
                clickable
                name="religionName"
                v-model="formParams.religionName"
                label="宗教信仰"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('religion')"
              />
              <van-field
                readonly
                clickable
                name="professionTypeName"
                v-model="formParams.professionTypeName"
                label="职业类别"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('professionType')"
              />
              <van-field
                name="profession"
                v-model="formParams.profession"
                label="职业"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
              />
              <van-field
                name="workPlace"
                v-model="formParams.workPlace"
                label="工作单位"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="100"
              />
              <van-field
                readonly
                clickable
                name="healthConditionName"
                v-model="formParams.healthConditionName"
                label="健康状况"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('healthCondition')"
              />
              <van-field
                name="phone"
                v-model="formParams.phone"
                label="联系方式"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.phone"
              />
              <van-field
                readonly
                clickable
                name="livingWayName"
                v-model="formParams.livingWayName"
                label="居住方式"
                placeholder="请选择"
                right-icon="arrow"
                @click="dictOpenPopup('livingWay')"
              />
              <van-field
                required
                readonly
                clickable
                name="regionCodeName"
                v-model="formParams.regionCodeName"
                label="所住区域"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.regionCodeName"
                @click="cascadeOpenPopup('regionCode', '所住区域')"
              />
              <van-field
                required
                name="address"
                v-model="formParams.address"
                label="现住详址"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="100"
                :rules="rules.address"
              />
            </van-collapse-item>
            <van-collapse-item size="large" title="补充信息" name="2">
              <!--本地户籍人口、非本地户籍人口-->
              <template v-if="formParams.residentType === '11' || formParams.residentType === '12'">
                <van-field
                  required
                  readonly
                  clickable
                  name="householdName"
                  v-model="formParams.householdName"
                  label="户籍地"
                  placeholder="请选择"
                  right-icon="arrow"
                  :rules="rules.householdName"
                  @click="cascadeOpenPopup('household', '户籍地')"
                />
                <van-field
                  required
                  name="householdAddress"
                  v-model="formParams.householdAddress"
                  label="户籍详址"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :maxlength="100"
                  :rules="rules.householdAddress"
                />
              </template>
              <!--本地户籍人口-->
              <template v-if="formParams.residentType === '11'">
                <van-field
                  readonly
                  clickable
                  name="identificationName"
                  v-model="formParams.identificationName"
                  label="人户分离标识"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dictOpenPopup('identification')"
                />
                <van-field
                  type="digit"
                  name="houseId"
                  v-model="formParams.houseId"
                  label="户号"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :maxlength="9"
                />
                <van-field
                  readonly
                  clickable
                  name="householdTypeName"
                  v-model="formParams.householdTypeName"
                  label="户口性质"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dictOpenPopup('householdType')"
                />
                <van-field
                  readonly
                  clickable
                  name="ownerRelationshipName"
                  v-model="formParams.ownerRelationshipName"
                  label="与户主关系"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dictOpenPopup('ownerRelationship')"
                />
                <template v-if="formParams.ownerRelationship !== '01'">
                  <van-field
                    readonly
                    clickable
                    name="ownerIdTypeName"
                    v-model="formParams.ownerIdTypeName"
                    label="户主证件类型"
                    placeholder="请选择"
                    right-icon="arrow"
                    :rules="rules.ownerIdTypeName"
                    @click="dictOpenPopup('ownerIdType')"
                  />
                  <van-field
                    name="ownerIdCard"
                    v-model="formParams.ownerIdCard"
                    label="户主证件号"
                    placeholder="请输入"
                    right-icon="arrow"
                    class="van-field__right-icon-white"
                    :rules="formParams.ownerIdType === '111' ? rules.ownerIdCard : rules.ownerPassport"
                  />
                </template>
              </template>
              <!--非本地户籍人口-->
              <template v-else-if="formParams.residentType === '12'">
                <van-field
                  readonly
                  clickable
                  name="householdTypeName"
                  v-model="formParams.householdTypeName"
                  label="户口性质"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dictOpenPopup('householdType')"
                />
                <van-field
                  required
                  readonly
                  clickable
                  name="flowCauseName"
                  v-model="formParams.flowCauseName"
                  label="流入原因"
                  placeholder="请选择"
                  right-icon="arrow"
                  :rules="rules.flowCauseName"
                  @click="dictOpenPopup('flowCause')"
                />
                <van-field
                  readonly
                  clickable
                  name="flowDate"
                  v-model="formParams.flowDate"
                  label="流入日期"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dateOpenPopup('flowDate')"
                />
                <van-field
                  readonly
                  clickable
                  name="cardTypeName"
                  v-model="formParams.cardTypeName"
                  label="办证类型"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dictOpenPopup('cardType')"
                />
                <van-field
                  name="cardNumber"
                  v-model="formParams.cardNumber"
                  label="办证号码"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :maxlength="30"
                  :rules="rules.cardNumber"
                />
                <van-field
                  readonly
                  clickable
                  name="registerDate"
                  v-model="formParams.registerDate"
                  label="办理日期"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dateOpenPopup('registerDate')"
                />
                <van-field
                  readonly
                  clickable
                  name="expireDate"
                  v-model="formParams.expireDate"
                  label="到期日期"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dateOpenPopup('expireDate')"
                />
                <van-field
                  readonly
                  clickable
                  name="residenceTypeName"
                  v-model="formParams.residenceTypeName"
                  label="住所类型"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dictOpenPopup('residenceType')"
                />
              </template>
              <!--境外来华停（居）留人员-->
              <template v-else-if="formParams.residentType === '20'">
                <van-field
                  required
                  name="lastName"
                  v-model="formParams.lastName"
                  label="外文姓"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :maxlength="50"
                  :rules="rules.lastName"
                />
                <van-field
                  required
                  name="firstName"
                  v-model="formParams.firstName"
                  label="外文名"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :maxlength="50"
                  :rules="rules.firstName"
                />
                <van-field
                  required
                  readonly
                  clickable
                  name="citizenshipName"
                  v-model="formParams.citizenshipName"
                  label="国籍（地区）"
                  placeholder="请选择"
                  right-icon="arrow"
                  :rules="rules.citizenshipName"
                  @click="dictOpenPopup('citizenship')"
                />
                <van-field
                  required
                  readonly
                  clickable
                  name="purposeName"
                  v-model="formParams.purposeName"
                  label="来华目的"
                  placeholder="请选择"
                  right-icon="arrow"
                  :rules="rules.purposeName"
                  @click="dictOpenPopup('purpose')"
                />
                <van-field
                  readonly
                  clickable
                  name="arriveTime"
                  v-model="formParams.arriveTime"
                  label="抵达日期"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dateOpenPopup('arriveTime')"
                />
                <van-field
                  readonly
                  clickable
                  name="leaveTime"
                  v-model="formParams.leaveTime"
                  label="预计离开日期"
                  placeholder="请选择"
                  right-icon="arrow"
                  @click="dateOpenPopup('leaveTime')"
                />
              </template>
              <van-field readonly required :label-width="300" :border="false">
                <template #label>
                  <span>上传照片</span>
                  <span class="van-field__label--tip">
                    <template v-if="formParams.pictureFeatureValue === '0'">（该照片已提取到特征值）</template>
                    <template v-else-if="formParams.pictureFeatureValue === '1'">（该照片未提取到特征值）</template>
                    <template v-else>（胸部以上正脸免冠照）</template>
                  </span>
                </template>
              </van-field>
              <van-field
                class="van-field__value--upload"
                input-align="left"
                error-message-align="left"
                :rules="rules.fileList"
              >
                <template #input>
                  <van-uploader
                    name="fileList"
                    v-model="fileList"
                    accept="image/*"
                    :preview-image="false"
                    :max-size="maxSize"
                    :before-read="uploadBeforeRead"
                    :after-read="uploadAfterRead"
                  >
                    <div class="van-uploader__input--yellow-small">
                      <van-image
                        v-if="fileList.length"
                        width="82px"
                        height="102px"
                        fit="cover"
                        style="border-radius: 12px"
                        :src="
                          fileList[fileList.length - 1].content || $config.ImageURl + fileList[fileList.length - 1].url
                        "
                      />
                      <template v-else>
                        <div class="upload-image"><van-icon class="iconImg" name="plus" size="16" /></div>
                        <div class="upload-text">不超过1M</div>
                      </template>
                    </div>
                  </van-uploader>
                </template>
              </van-field>
            </van-collapse-item>
          </van-collapse>
          <van-cell size="large" title="房屋绑定">
            <template #right-icon>
              <van-tag size="large" color="#ffffff" text-color="#3B99DA" @click="$refs.houseFrom.submit()">
                绑定
              </van-tag>
            </template>
          </van-cell>
          <van-form
            validate-trigger="onSubmit"
            :show-error="false"
            ref="houseFrom"
            input-align="right"
            error-message-align="right"
            :label-width="120"
            @submit="houseOnSubmit"
          >
            <van-field
              required
              readonly
              clickable
              v-model="houseFormParams.placeName"
              label="所属场所"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.placeName"
              @input="getBuild"
              @click="houseOpenPopup('place')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="houseFormParams.buildName"
              label="楼栋"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.buildName"
              @input="getUnit"
              @click="houseOpenPopup('build')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="houseFormParams.unitName"
              label="单元"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.unitName"
              @input="getFloor"
              @click="houseOpenPopup('unit')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="houseFormParams.floorName"
              label="楼层"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.floorName"
              @click="houseOpenPopup('floor')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="houseFormParams.houseName"
              label="房间号"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.houseName"
              @click="houseOpenPopup('house')"
            />
            <van-field
              required
              readonly
              clickable
              name="registerTypeName"
              v-model="houseFormParams.registerTypeName"
              label="登记类型"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.registerTypeName"
              @click="dictOpenPopup('registerType', 'houseFormParams')"
            />
            <van-field
              v-if="houseFormParams.registerType === '2'"
              required
              readonly
              clickable
              name="expirationData"
              v-model="houseFormParams.expirationData"
              label="租住截至日期"
              placeholder="请选择"
              right-icon="arrow"
              :rules="houseRules.expirationData"
              @click="dateOpenPopup('expirationData', 'houseFormParams')"
            />
          </van-form>
          <div class="van-collapse" v-if="formParams.houseInfo.length">
            <van-tabs border>
              <van-tab
                v-for="(item, key) in formParams.houseInfo"
                :key="key"
                :title="`房屋${toChinesNum(key + 1)}`"
                :name="item.code"
              >
                <van-field readonly label="房屋信息" size="large">
                  <template #right-icon>
                    <van-tag
                      size="large"
                      color="#ffffff"
                      text-color="#E28556"
                      @click="formParams.houseInfo.splice(key, 1)"
                    >
                      解绑
                    </van-tag>
                  </template>
                </van-field>
                <van-field readonly label="所属场所" v-model="item.placeName"></van-field>
                <van-field readonly label="楼栋名称" v-model="item.buildName"></van-field>
                <van-field readonly label="单元名称" v-model="item.unitName"></van-field>
                <van-field readonly label="楼层" v-model="item.floorName"></van-field>
                <van-field readonly label="房间号" v-model="item.houseName"></van-field>
                <van-field readonly label="登记类型" v-model="item.residentTypeName"></van-field>
                <van-field
                  v-if="item.registerType === '2' || item.personType === '2'"
                  readonly
                  label="租住截至日期"
                  v-model="item.expirationData"
                />
              </van-tab>
            </van-tabs>
          </div>
          <div style="padding: 16px">
            <template v-if="$route.query.type === 'Update'">
              <van-button block type="info" native-type="submit" :disabled="buttonDisabled">更新</van-button>
            </template>
            <template v-else-if="$route.query.type === 'Approve'">
              <van-row :gutter="20">
                <van-col :span="12">
                  <van-button
                    block
                    native-type="button"
                    @click="
                      $router.push(
                        `/resident/audit/reject?code=${formParams.personCode}&baseType=${$route.query.baseType}`
                      )
                    "
                  >
                    驳回
                  </van-button>
                </van-col>
                <van-col :span="12">
                  <van-button block type="info" native-type="submit" :disabled="buttonDisabled">通过</van-button>
                </van-col>
              </van-row>
            </template>
            <template v-else>
              <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
            </template>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
        @change="dictOnChange"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
      <van-datetime-picker
        v-model="date"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="datePopupShow = false"
        @confirm="dateOnConfirm"
      />
    </van-popup>
    <!-- 联级 -->
    <van-popup v-model="cascadePopupShow" round position="bottom" @close="cascadeValue = ''">
      <van-cascader
        v-model="cascadeValue"
        :title="cascadeTitle"
        :options="cascadeData[cascadeType]"
        :field-names="{ text: 'title', value: 'code' }"
        :closeable="false"
        @finish="cascadeOnFinish"
      />
    </van-popup>
    <!-- 所属场所 -->
    <van-popup v-model="housePopupShow" round position="bottom">
      <van-picker
        show-toolbar
        :default-index="
          houseData[`${houseType}Data`] &&
          houseData[`${houseType}Data`].findIndex(o => o.code === houseFormParams[`${houseType}Code`])
        "
        :columns="houseData[`${houseType}Data`]"
        value-key="title"
        @cancel="housePopupShow = false"
        @confirm="houseOnConfirm"
      />
    </van-popup>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Upload from '@/mixins/upload'
import SelectPopup from '@/mixins/selectPopup'
import General from '@/api/general'
import Resident from '@/api/resident'
import { toChinesNum } from '@/libs/tool'
import { formParams, HouseFormParams } from './libs/person'
import { residentNameReg, idCardCheck, phoneReg, passPortCardReg, alphaNumber } from '@/libs/regexp'
export default {
  mixins: [Upload, SelectPopup],
  data() {
    const phoneRegValidator = () => {
      return this.formParams.phone && phoneReg.test(this.formParams.phone)
    }
    const ownerIdTypeNameValidator = () => {
      if (!this.formParams.ownerIdCard && this.formParams.ownerIdType) {
        return true
      } else if (this.formParams.ownerIdCard && !this.formParams.ownerIdType) {
        return false
      }
    }
    const idCardCheckValidator = () => {
      return this.formParams.ownerIdCard && idCardCheck(this.formParams.ownerIdCard)
    }
    const passPortCardRegValidator = () => {
      return this.formParams.ownerIdCard && passPortCardReg.test(this.formParams.ownerIdCard)
    }
    return {
      toChinesNum,
      title: '采集',
      activeNames: ['1', '2'],
      folder: 'approve/person',
      idCardFolder: 'approve/idCard/img',
      maxSize: 10 * 1024 * 1024,
      idCardFileList: [],
      fileList: [],

      buttonDisabled: false,
      formParams: { ...formParams, houseInfo: [] },
      rules: {
        residentTypeName: [{ required: true, message: '请选择人口管理类型' }],
        personName: [
          { required: true, message: '请输入姓名' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        formerName: [{ pattern: residentNameReg, message: '请输入中文、英文和"·"' }],
        idTypeName: [{ required: true, message: '请选择证件类型' }],
        idCard: [
          { required: true, message: '请输入证件号' },
          { validator: idCardCheck, message: '请输入正确的证件号' }
        ],
        passport: [
          { required: true, message: '请输入证件号' },
          { pattern: passPortCardReg, message: '请输入正确的证件号' }
        ],
        sexName: [{ required: true, message: '请选择性别' }],
        nationalityName: [{ required: true, message: '请选择民族' }],
        phone: [{ validator: phoneRegValidator, message: '请输入正确的手机号' }],
        regionCodeName: [{ required: true, message: '请选择所属区域' }],
        address: [{ required: true, message: '请输入现住祥址' }],

        // 补充信息
        householdName: [{ required: true, message: '请选择户籍地' }],
        householdAddress: [{ required: true, message: '请输入户籍详址' }],
        // 本地户籍人口
        ownerIdTypeName: [{ validator: ownerIdTypeNameValidator, message: '请选择证件类型' }],
        ownerIdCard: [{ validator: idCardCheckValidator, message: '请输入正确的证件号' }],
        ownerPassport: [{ validator: passPortCardRegValidator, message: '请输入正确的证件号' }],

        // 非本地户籍人口
        flowCauseName: [{ required: true, message: '请选择流入原因' }],
        cardNumber: [{ pattern: alphaNumber, message: '请输入字母或数字' }],

        // 境外来华停（居）留人员
        lastName: [{ required: true, message: '请输入外文姓' }],
        firstName: [{ required: true, message: '请输入外文名' }],
        citizenshipName: [{ required: true, message: '请选择国籍（地区）' }],
        purposeName: [{ required: true, message: '请选择来华目的' }],

        fileList: [{ required: true, message: '请上传照片' }]
      },
      // 房屋信息
      houseFormParams: new HouseFormParams(),
      houseData: {
        placeData: [],
        buildData: [],
        unitData: [],
        floorData: [],
        houseData: []
      },
      houseRules: {
        registerTypeName: [{ required: true, message: '请选择登记类型' }],
        placeName: [{ required: true, message: '请选择所属场所' }],
        buildName: [{ required: true, message: '请选择楼栋' }],
        unitName: [{ required: true, message: '请选择单元' }],
        floorName: [{ required: true, message: '请选择楼层' }],
        houseName: [{ required: true, message: '请选择房间号' }],
        expirationData: [{ required: true, message: '请选择租住截至日期' }]
      },
      // 房屋信息
      houseType: '',
      housePopupShow: false,
      dictTypes:
        'residentType,registerType,idType,sex,nationality,marriage,politic,edulevel,religion,professionType,healthCondition,livingWay,identification,householdType,ownerRelationship,flowCause,cardType,residenceType,citizenship,purpose'
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  watch: {
    'houseFormParams.placeCode'() {
      this.getBuild()
    },
    'houseFormParams.buildCode'() {
      this.getUnit()
    },
    'houseFormParams.unitCode'() {
      this.getFloor()
    },
    'houseFormParams.floorCode'() {
      this.getHouse()
    }
  },
  created() {
    // this.formParams.residentType = this.$route.query.residentType
    // this.formParams.residentTypeName = this.$route.query.residentTypeName
    // 字典项
    this.getDict(this.dictTypes)
    // 籍贯、户籍地
    this.getCitytodis()
    // 所住区域
    this.getTree()
    // this.getAreaTree()
    // 所属场所
    this.getPlace()

    // 更新
    if (this.$route.query.personCode) {
      this.title = this.$route.query.type === 'Update' ? '更新' : '审核'
      this.getDetail()
    }
  },
  methods: {
    // 获取详情
    getDetail() {
      Resident.BaseInfo.residentDetail({
        personCode: this.$route.query.personCode,
        baseType: this.$route.query.baseType,
        queryType: this.$route.query.queryType
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.formParams = { ...data[0].personInfo, houseInfo: data[0].houseInfo }
          if (this.formParams.personImage) {
            this.fileList = [
              {
                url: this.formParams.personImage
              }
            ]
          }
        }
      })
    },
    // 根据证件号码带入人员信息
    queryDetail() {
      Resident.Init.residentCheck({
        regionCode: this.user.regionCode,
        idCard: this.formParams.idCard,
        personCode: this.$route.query.personCode
      }).then(res => {
        const { status, data } = res.data
        if (status === 0 && data) {
          this.formParams = { ...data[0].personInfo, houseInfo: data[0].houseInfo }
          if (this.formParams.personImage) {
            this.fileList = [
              {
                url: this.formParams.personImage
              }
            ]
          }
        }
      })
    },
    // 籍贯、户籍地
    getCitytodis() {
      General.Region.getCitytodis().then(res => {
        this.cascadeData.birthPlace = res.data.data
        this.cascadeData.household = res.data.data
      })
    },
    // 所住区域
    getTree() {
      General.Region.getTree({
        regionCode: this.user.regionCode
      }).then(res => {
        this.cascadeData.regionCode = res.data.data
      })
    },
    // getAreaTree() {
    //   General.Region.getTree(params).then(res => {
    //     const resData = res.data.data
    //     const map = {
    //       value: 'code',
    //       label: 'title',
    //       children: 'children'
    //     }
    //     this.areaList = recursion.convertTree(resData, map)
    //   })
    // },
    dictOnChange() {
      if (this.dictType === 'registerType') this.houseFormParams.expirationData = ''
    },
    // 身份证信息识别
    uploadAfter(detail) {
      if (detail.name === 'fileList') {
        Resident.Init.residentFeature({
          path: this.fileList[this.fileList.length - 1].url
        }).then(res => {
          if (res.data.status === 0) {
            this.formParams.pictureFeatureValue = '0'
          } else if (res.data.status === 500) {
            this.formParams.pictureFeatureValue = '1'
          }
        })
      } else if (detail.name === 'idCardFileList') {
        Resident.Init.getPersonInfo({
          imgUrl: this.idCardFileList[this.idCardFileList.length - 1].url
        }).then(res => {
          const { status, data } = res.data
          if (status === 0) {
            this.formParams.idType = '111'
            this.formParams.idTypeName = '居民身份证'
            this.formParams.birthday = data.birth
            this.formParams.householdAddress = data.householdAddress
            this.formParams.idCard = data.idCard
            this.formParams.nationality = data.nationality
            this.formParams.nationalityName = data.nationalityName
            this.formParams.personName = data.personName
            this.formParams.sex = data.sex
            this.formParams.sexName = data.sexName
            this.formParams.residentType = data.residentType
          } else {
            this.$toast('身份证信息读取失败')
          }
        })
      }
    },
    // 房屋所属场所
    getPlace() {
      // this.houseData = {
      //   placeData: [],
      //   buildData: [],
      //   unitData: [],
      //   floorData: [],
      //   houseData: []
      // }
      // this.houseFormParams.placeCode = ''
      // this.houseFormParams.placeName = ''
      // this.houseFormParams.buildCode = ''
      // this.houseFormParams.buildName = ''
      // this.houseFormParams.unitCode = ''
      // this.houseFormParams.unitName = ''
      // this.houseFormParams.floorCode = ''
      // this.houseFormParams.floorName = ''
      // this.houseFormParams.houseCode = ''
      // this.houseFormParams.houseName = ''
      const params = {
        regionCode: this.user.regionCode
      }
      General.Region.getPlace(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.placeData = data
        }
      })
    },
    getBuild() {
      this.houseData = {
        placeData: this.houseData.placeData,
        buildData: [],
        unitData: [],
        floorData: [],
        houseData: []
      }
      this.houseFormParams.buildCode = ''
      this.houseFormParams.buildName = ''
      this.houseFormParams.unitCode = ''
      this.houseFormParams.unitName = ''
      this.houseFormParams.floorCode = ''
      this.houseFormParams.floorName = ''
      this.houseFormParams.houseCode = ''
      this.houseFormParams.houseName = ''
      const params = {
        placeCode: this.houseFormParams.placeCode
      }
      General.Region.getBuild(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.buildData = data
        }
      })
    },
    getUnit() {
      this.houseData = {
        placeData: this.houseData.placeData,
        buildData: this.houseData.buildData,
        unitData: [],
        floorData: [],
        houseData: []
      }
      this.houseFormParams.unitCode = ''
      this.houseFormParams.unitName = ''
      this.houseFormParams.floorCode = ''
      this.houseFormParams.floorName = ''
      this.houseFormParams.houseCode = ''
      this.houseFormParams.houseName = ''
      const params = {
        buildCode: this.houseFormParams.buildCode
      }
      General.Region.getUnit(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.unitData = data
        }
      })
    },
    getFloor() {
      this.houseData.floorData = []
      this.houseData.houseData = []
      this.houseFormParams.floorCode = ''
      this.houseFormParams.floorName = ''
      this.houseFormParams.houseCode = ''
      this.houseFormParams.houseName = ''
      const params = {
        buildCode: this.houseFormParams.buildCode,
        unit: this.houseFormParams.unitCode
      }
      General.Region.getFloor(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.floorData = data
        }
      })
    },
    getHouse() {
      this.houseData.houseData = []
      this.houseFormParams.houseCode = ''
      this.houseFormParams.houseName = ''
      const params = {
        buildCode: this.houseFormParams.buildCode,
        unit: this.houseFormParams.unitCode,
        floor: this.houseFormParams.floorCode
      }
      General.Region.getHouse(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.houseData = data
        }
      })
    },
    houseOpenPopup(houseType) {
      if (!this.houseData[`${houseType}Data`].length) {
        this.$toast('暂无数据')
        return false
      }
      this.houseType = houseType
      this.housePopupShow = true
    },
    houseOnConfirm(item) {
      this.houseFormParams[`${this.houseType}Code`] = item.code
      this.houseFormParams[`${this.houseType}Name`] = item.title
      this.housePopupShow = false
    },
    // 表单 - 房屋信息
    houseOnSubmit() {
      this.formParams.houseInfo.push({
        ...this.houseFormParams,
        communityCode: this.formParams.regionCode,
        personType: this.houseFormParams.registerType,
        expirationData: this.houseFormParams.expirationData,
        residentTypeName: this.houseFormParams.registerTypeName
      })
      this.houseFormParams = new HouseFormParams()
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      if (!this.formParams.houseInfo.length) {
        this.$dialog.alert({
          title: '提示',
          message: '请绑定房屋信息'
        })
        return false
      }
      this.buttonDisabled = true
      this.formParams.personImage = this.fileList[this.fileList.length - 1].url
      Resident.BaseInfo[`resident${this.$route.query.type || 'Save'}`](this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$router.push({
              path: '/page/message',
              query: {
                backTo: this.$route.query.type ? '-2' : '-1',
                title: this.$route.query.type ? `${this.title}成功` : '提交成功'
              }
            })
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/assets/style/resident/detail.less';
</style>
